<template>
  <div class="video-page">
    <!-- 左边为视频窗口 -->
    <div class="video-container" >
      <video :src="videoUrl" controls width="100%" height="100%" :key="componentKey"></video>
    </div>
    <!-- 右边为章节选择和评论输入 -->
    <div class="sidebar">
      <!-- 课程名称 -->
      <h2>{{ course_details.courseName }}</h2>
      <div class="demo-progress">
        <el-progress :percentage="percentage" :stroke-width="20" :color="customColorMethod" />
      </div>
      <!-- 章节选择 -->
      <div class="chapter-select">
        <h3>选择章节</h3>
        <ul>
          <li v-for="chapter in chapters" :key="chapter.id" @click="handleChapterSelect(chapter)">
            {{ chapter.chapterName }}
          </li>
        </ul>
      </div>
      <!-- 评论输入 -->
      <div class="comment-section">
        <h3>评论</h3>
        <textarea v-model="commentText" placeholder="输入评论..."></textarea>
        <el-button link type="primary" icon="Edit" @click="submitComment" v-hasPermi="['manage:evaluation:add']">提交评论</el-button>
        <ul>
          <li v-for="item in comments" :key="item.id">{{ item.content }}</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { listCourse, getCourse, delCourse, addCourse, updateCourse } from '@/api/manage/course_details';
import { listChapter } from '@/api/manage/chapter';
import { listCourseType } from '@/api/manage/courseType';
import { ref, onMounted, watch, reactive, toRefs } from 'vue';
import { useRoute } from 'vue-router';
import { getCurrentInstance } from '@vue/runtime-core';
// import getInfo from "@/store/modules/user";
import {getInfo} from '@/api/login'
import {addEvaluation,getEvaluationBycouresid} from "@/api/manage/evaluation";
// import log from 'video.js/dist/types/utils/log';
import { addProgress,listProgress } from "@/api/manage/progress";
import { Minus, Plus } from '@element-plus/icons-vue'


const route = useRoute();
const { proxy } = getCurrentInstance();

const courseList = ref([]);
const loading = ref(true);
const total = ref(0);
const courseIdFromRoute = ref(null);

//进度
const percentage = ref(0)

const data = reactive({
  userid: 0,
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    classNumber: null,
    courseName: null,
    courseTypeId: null,
    teacherId: null,
    courseStatus: null,
  },
});

const { queryParams } = toRefs(data);
function getinfo(){
  getInfo().then(response => {
    data.userid = response.user.userId;

    console.log(response.user.userId);
    console.log(data.userid);

    
  });
}

/** 查询课程展示列表 */
function getList() {
  loading.value = true;
  listCourse(queryParams.value).then(response => {
    courseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取课程分类列表 */
function getCourseTypeList() {
  listCourseType(queryParams.value).then(response => {
    console.log(response.rows);
  });
}

// 在组件挂载时执行的逻辑
onMounted(() => {
  getCourseTypeList();
  getList();
  // 默认加载章节ID为1的视频
  // handleChapterSelect(1);
  //加载当前的用户数据
  getinfo();
  //获取当前课程的评论信息
  getEvaluationList(route.params.id);
});

// 监听路由变化
watch(
  () => route,
  (newRoute) => {

    courseIdFromRoute.value = newRoute.query.id;
    if (courseIdFromRoute.value) {
      loadCourseDetails(courseIdFromRoute.value);
    }
  },
  { immediate: true }
);

/** 查询课程详情 */
function loadCourseDetails(id) {
  getCourse(id).then(response => {
    // 假设我们需要在课程列表中高亮显示该课程
    const foundCourse = courseList.value.find(course => course.id === id);
    if (foundCourse) {
      Object.assign(foundCourse, response.data);
    } else {
      // 如果课程不在当前列表中，我们可以将其添加到列表前端或后端
      courseList.value.unshift(response.data);
    }
  });
}

/** 处理课程选择事件 */
function handleSelect(row) {
  // 根据需要处理选择事件，例如导航到课程详情页面
  // proxy.$router.push({ name: 'CourseDetail', params: { id: row.id } });
}

/** 查询字典类型详细 */
const course_details = ref({});
const course_id = ref();
function getTypes(id) {
  course_id.value = id;
  console.log(course_id);
  console.log(course_id.value);
  getCourse(id).then(response => {
    course_details.value = response.data;
    getList();
  });
}

const videoUrl = ref(null);
const componentKey = ref(1);
function handleChapterSelect(row) {
  videoUrl.value = null;
  // 对章节进行遍历，找到对应的数据
  chapters.value.forEach(chapter => {
    if (chapter.id === row.id) {
      videoUrl.value = chapter.chapterVideoUrl;
      componentKey.value += 1;
      //打印ta.value.chapterId = chapter.id;
      // console.log(chapter);
      console.log(componentKey);
    }
    
  })
  // 记录进度
  console.log({ sectionId:row.id, courseId:row.courseId });
  
  addProgress({ sectionId:row.id, courseId:row.courseId }).then(response =>{
    getPercentage(route.params.id)
  })

  console.log(videoUrl);
}

// 定义一个响应式对象
const evaluationData = reactive({});

// 初始化数据结构


const commentText = ref('');
const comments = ref({});
//提交评论
function submitComment() {
  if (commentText.value.trim()) {
    // comments.value.push({ id: Date.now(), text: commentText.value });
    getinfo();
    data.form.userId = data.userid;
    console.log(data.form.userId);
    data.form.content = commentText.value;
    console.log(data.form.comment);
    data.form.courseId = route.params.id;
    console.log(data.form);
    
    addEvaluation(data.form).then(response => {
      proxy.$modal.msgSuccess("评论成功");
    })
    commentText.value = '';
  }
}

/**根据课程id查询评论信息 */
function getEvaluationList(courseId) {
  // route.params.id
  const _id = courseId;
  getEvaluationBycouresid(_id).then(response => {
    comments.value = response.rows;
  });
}

// reset();
//   const _id = row.id || ids.value
//   getEvaluation(_id).then(response => {
//     form.value = response.data;
//     open.value = true;
//     title.value = "修改课程评价";
//   });

/**根据课程id查询章节信息 */
const chapters = ref([]);
function getChapterList(courseId) {
  listChapter({ courseId }).then(response => {
    chapters.value = response.rows;
  });
}

/**点击章节后的操作 */
function getChapter(courseId) {
  getChapterList(courseId);
}

/**进度百分比 */
const customColorMethod = (percentage: number) => {
  if (percentage < 30) {
    return '#909399'
  }
  if (percentage < 70) {
    return '#e6a23c'
  }
  return '#67c23a'
}

/** 获取课程进度 */
const getPercentage = (id)=>{
  listProgress({courseId:id}).then(response =>{
    console.log(response.rows);
    
    if(response.rows !== undefined && response.rows.length !== 0){
      percentage.value = response.rows[0].completionPercentage;

    }
  });
  
}

getChapterList(route.params.id);
getTypes(route.params && route.params.id);
getPercentage(route.params.id)
</script>

<style scoped>
.video-page {
  display: flex;
}

.video-container {
  width: 70%;
  height: 80%;
  flex: 3;
  padding: 20px;
}

.sidebar {
  flex: 1;
  padding: 20px;
  background-color: #f5f5f5;
}

.chapter-select ul {
  list-style-type: none;
  padding: 0;
}

.chapter-select li {
  cursor: pointer;
  padding: 10px;
  background-color: #fff;
  margin-bottom: 10px;
  border: 1px solid #ddd;
}

.chapter-select li:hover {
  background-color: #eee;
}

.comment-section textarea {
  width: 100%;
  height: 100px;
  margin-bottom: 10px;
}

.comment-section button {
  display: block;
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  cursor: pointer;
}

.comment-section button:hover {
  background-color: #0056b3;
}

.comment-section ul {
  list-style-type: none;
  padding: 0;
}

.comment-section li {
  background-color: #fff;
  padding: 10px;
  border: 1px solid #ddd;
  margin-bottom: 10px;
}
</style>